/*
 * C_CRC16.c
 *
 *  Created on: Sep 17, 2025
 *      Author: ADMIN
 */

#include "C_CRC16.h"

uint8_t CRCCheck(uint8_t data[], int length)
{
    // 如果数组长度小于3（至少1个数据字节+2个CRC字节），则CRC检查失败
    if (length < 3)
    {
        return 0;
    }
    
    // 提取最后两个字节作为存储的CRC值
    uint16_t storedCRC = (data[length - 2] << 8) | data[length - 1];
    
    // 计算前面数据的CRC（不包括最后两个CRC字节）
    uint16_t calculatedCRC = CalculateCRC16(data, length - 2);
    
    // 比较计算出的CRC和存储的CRC
    if (calculatedCRC == storedCRC)
    {
        return 1;  // CRC检查通过
    }
    else
    {
        return 0;  // CRC检查失败
    }
}

uint16_t CalculateCRC16(uint8_t data[], int length)
{
    uint16_t crc = 0xFFFF;
    uint16_t polynomial = 0xA001;

    for (int j = 0; j < length; j++)
    {
        crc ^= data[j];
        for (int i = 0; i < 8; i++)
        {
            if ((crc & 0x0001) != 0)
            {
                crc = (crc >> 1) ^ polynomial;
            }
            else
            {
                crc = crc >> 1;
            }
        }
    }
    return crc;
}

uint8_t compare_arrays(uint8_t* a, uint8_t* b, int size)
{
    for (int i = 0; i < size; i++) {
        if (a[i] != b[i]) {
            return 0;
        }
    }
    return 1;
}
